require 'rubygems'
require 'blather'
require 'pp'

include Blather

module Epic
	class Service
		ADHOC_CMDS = Stanza::Iq::Command.registered_ns
		FORM_NS = XMPPNode::Form.registered_ns
		attr_accessor :identity, :features

		def initialize(client,config=nil)
			@client = client
#			@config = YAML.load_file(config)
#			@features = @config['features']
			@features = ['gettime','onoff', 'execute']

			## return ad hoc command for plain feature list
			@client.register_handler(:disco_info) do |info| 
				resp = Stanza::Disco::DiscoInfo.import(info)
				resp.query << Stanza::Disco::DiscoInfo::Feature.new(ADHOC_CMDS)
				if info.node  != nil
					resp.query << Stanza::Disco::DiscoInfo::Identity.new(info.node,:command,:automation)
					resp.query << Stanza::Disco::DiscoInfo::Feature.new(FORM_NS)
				end
				@client.write resp.reply
			end


			## return ad hoc commands as nodes in items request
			@client.register_handler(:disco_items) do |items|
				resp = Stanza::Disco::DiscoItems.import(items)
				if ADHOC_CMDS == items.node 
					@features.each do |f| 
						resp.query << Stanza::Disco::DiscoItems::Item.new(client.jid,f,f)
					end
				end
				@client.write resp.reply
			end

			@client.register_handler(:command) do |cmd|
				@client.write cmd.reply
			end
		end

		def add_features(info)
			mine = Stanza::Disco::DiscoInfo.import(info)
			@features.each do |f|
				mine.query << Stanza::Disco::DiscoInfo::Feature.new(f)
			end
			mine
		end

		def to_s
			puts @features
		end
	end
end

